package com.myfir.dao;

import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.myfir.entity.User;

public class UserDAO extends HibernateDaoSupport {

	public void delete(User user) throws Exception {
		this.getHibernateTemplate().delete(user);
	}

	public void save(User user) throws Exception {
		this.getHibernateTemplate().save(user);
	}

	@SuppressWarnings("unchecked")
	public User findById(int id) throws Exception {
		String hql = "from User where id=?";
		List<User> list = this.getHibernateTemplate().find(hql,
				new Object[] { id });
		User user = null;
		if (!list.isEmpty()) {
			user = list.get(0);
		}
		return user;
	}

	@SuppressWarnings("unchecked")
	public List<User> findAll() throws Exception {
		String hql = "from User";
		List<User> list = this.getHibernateTemplate().find(hql);
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<User> searchByKeyword(String keyword) throws Exception {
		keyword = "%" + keyword + "%";
		System.out.println(keyword);
		String hql = "from User where name like ?";
		List<User> list = this.getHibernateTemplate().find(hql,
				new Object[] { keyword });
		return list;
	}

	public void updateById(User user) {
		this.getHibernateTemplate().update(user);
	}

	public void updateByName(User user) throws Exception {
		this.getHibernateTemplate().update(user);
	}

	@SuppressWarnings("unchecked")
	public User findByName(String name) throws Exception {
		String hql = "from User where name=?";
		User user = null;
		List<User> list = this.getHibernateTemplate().find(hql,
				new Object[] { name });
		if (!list.isEmpty()) {
			user = list.get(0);
		}
		return user;
	}
}